package com.dao;

import java.sql.Timestamp;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;

import com.base.BaseDao;
import com.base.PageBean;
import com.bean.ParkManager;
import com.bean.Parkinfo;
import com.bean.ParkinfoManagerRelevance;
import com.util.GUtil;

/**
 * A data access object (DAO) providing persistence and search support for Parkinfo entities.
 * Transaction control of the save(), update() and delete() operations 
		can directly support Spring container-managed transactions or they can be augmented	to handle user-managed Spring transactions. 
		Each of these methods provides additional information for how to configure it for the desired type of transaction control. 	
 * @see com.bean.Parkinfo
 * @author MyEclipse Persistence Tools 
 */
public class ParkinfoDao extends BaseDao  {
	private static final Logger log = Logger.getLogger(ParkinfoDao.class);
	//property constants
	public static final String _PNAME = "PName";
	public static final String _PDESC = "PDesc";
	public static final String _PTYPE = "PType";
	public static final String DAY_PRICE = "dayPrice";
	public static final String NIGHT_PRICE = "nightPrice";
	public static final String ORDERABLE = "orderable";
	public static final String ADDR = "addr";
	public static final String TELE_PHONE = "telePhone";
	public static final String REMAINDER_PARK_NUMBER = "remainderParkNumber";
	public static final String PARK_NUMBER = "parkNumber";
	public static final String SCORE = "score";
	public static final String LONGITUDE = "longitude";
	public static final String LATITUDE = "latitude";
	public static final String SOURCE = "source";
	public static final String DAY_TIME_UTIL = "dayTimeUtil";
	public static final String NIGHT_TIME_UTIL = "nightTimeUtil";
	public static final String SWITCH_EDIT_AMOUNT = "switchEditAmount";
	public static final String SWITCH_GRATUITY = "switchGratuity";
	public static final String IS_FREE = "isFree";
	public static final String MIN_GRATUITY = "minGratuity";
	public static final String COMMENT_COUNT = "commentCount";
	public static final String TRADE_COUNT = "tradeCount";
	public static final String ATTRIBUTION = "attribution";
	public static final String BUSINESS_NO = "businessNo";
	public static final String ENTERPRISE_NAME = "enterpriseName";
	public static final String STATUS = "status";


	/**
	 * <p>Title: getMyParkArea</p>
	 * <p>Description: 首先读取我的停车场ID，在通过ID获取停车场信息 </p>
	 * @param pm
	 * @return
	 * @throws Exception
	 */
	public List<Parkinfo> getMyParkArea(ParkManager pm) throws Exception {
		ParkinfoManagerRelevance pmr = null;
		String hql = " from Parkinfo where status!=-1 and PId in( select PId from ParkinfoManagerRelevance where userId=? )";
		Query query= getSession().createQuery(hql);
		query.setLong(0, pm.getUserId());
		return query.list();
	}
	public List query(Parkinfo parkInfo, PageBean page) {
		log.debug("query Parkinfo List instances");
		session = getSession();
		try {
			String hql = "from Parkinfo where 1=1 ";
			String where = "";
			if(parkInfo!=null){
				if(parkInfo.getPName()!=null && !parkInfo.getPName().trim().isEmpty())
					where += " and PName like '%"+parkInfo.getPName()+"%'";
				if(parkInfo.getAddr()!=null && !parkInfo.getAddr().trim().isEmpty())
					where += " and addr like '%"+parkInfo.getAddr()+"%'";
				if(parkInfo.getTelePhone()!=null && !parkInfo.getTelePhone().trim().isEmpty())
					where += " and telePhone like '%"+parkInfo.getTelePhone()+"%'";
				if(parkInfo.getPType()!=null )
					where += " and PType="+parkInfo.getPType();
			}
			String order = " order by id desc ";
			String sql = hql + where + order;
			Long count = (Long) session.createQuery("select count(*) "+ sql).uniqueResult();
			
			if(page!=null && count!=null )
				page.setTotalRow(count.intValue());
			
			Query query = session.createQuery(sql);
			if(page!=null && page.getPageSize()>0 && page.getCurrentPage()>0){
				query.setFirstResult( (page.getCurrentPage()-1)*page.getPageSize());
				query.setMaxResults( page.getPageSize() );
			}
			return query.list();
		} catch (RuntimeException re) {
			log.error(this.getClass()+".query() query failed", re);
			throw re;
		}
	}


	public String update(Parkinfo transientInstance) {
		log.debug("saving Parkinfo instance");
		session = getSession();
		try {
//			session.clear();
			session.merge(transientInstance);
			session.flush();
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
		return GUtil.SUCCESS;
	}

	public String addParkinfoManagerRelevance(ParkinfoManagerRelevance pmr){
		log.debug("saving ParkinfoManagerRelevance instance");
		try {
			getSession().save(pmr);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
		return GUtil.SUCCESS;
	}

	public Parkinfo merge(Parkinfo detachedInstance) {
		log.debug("merging Parkinfo instance");
		try {
			Parkinfo result = (Parkinfo) getSession()
					.merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public String save(Parkinfo transientInstance) {
		log.debug("saving Parkinfo instance");
		try {
			getSession().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
		return GUtil.SUCCESS;
	}

	public String delete(Integer id, Integer flag){
		Parkinfo pk = this.findById(id);
		if(pk!=null)
			return delete(pk, flag);
		else
			return GUtil.FAILE;
	}

	public String delete(Parkinfo persistentInstance,Integer flag) {
		log.debug("deleting Parkinfo instance");
		try {
			if(flag==null)
				getSession().delete(persistentInstance);
			else{
				persistentInstance.setStatus(flag.shortValue());
				getSession().update(persistentInstance);
			}
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
		return GUtil.SUCCESS;
	}

	public Parkinfo findById( java.lang.Integer id) {
		log.debug("getting Parkinfo instance with id: " + id);
		try {
			Parkinfo instance = (Parkinfo) getSession().get(Parkinfo.class, id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed id="+id, re);
			throw re;
		}
	}


	public List findByExample(Parkinfo instance) {
		log.debug("finding Parkinfo instance by example");
		try {
			List results = getSession()
					.createCriteria(Parkinfo.class)
					.add(Example.create(instance))
					.list();
			log.debug("find by example successful, result size: " + results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}    

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Parkinfo instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Parkinfo as model where model." 
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByPName(Object PName
			) {
		return findByProperty(_PNAME, PName
				);
	}

	public List findByPDesc(Object PDesc
			) {
		return findByProperty(_PDESC, PDesc
				);
	}

	public List findByPType(Object PType
			) {
		return findByProperty(_PTYPE, PType
				);
	}

	public List findByDayPrice(Object dayPrice
			) {
		return findByProperty(DAY_PRICE, dayPrice
				);
	}

	public List findByNightPrice(Object nightPrice
			) {
		return findByProperty(NIGHT_PRICE, nightPrice
				);
	}

	public List findByOrderable(Object orderable
			) {
		return findByProperty(ORDERABLE, orderable
				);
	}

	public List findByAddr(Object addr
			) {
		return findByProperty(ADDR, addr
				);
	}

	public List findByTelePhone(Object telePhone
			) {
		return findByProperty(TELE_PHONE, telePhone
				);
	}

	public List findByRemainderParkNumber(Object remainderParkNumber
			) {
		return findByProperty(REMAINDER_PARK_NUMBER, remainderParkNumber
				);
	}

	public List findByParkNumber(Object parkNumber
			) {
		return findByProperty(PARK_NUMBER, parkNumber
				);
	}

	public List findByScore(Object score
			) {
		return findByProperty(SCORE, score
				);
	}

	public List findByLongitude(Object longitude
			) {
		return findByProperty(LONGITUDE, longitude
				);
	}

	public List findByLatitude(Object latitude
			) {
		return findByProperty(LATITUDE, latitude
				);
	}

	public List findBySource(Object source
			) {
		return findByProperty(SOURCE, source
				);
	}

	public List findByDayTimeUtil(Object dayTimeUtil
			) {
		return findByProperty(DAY_TIME_UTIL, dayTimeUtil
				);
	}

	public List findByNightTimeUtil(Object nightTimeUtil
			) {
		return findByProperty(NIGHT_TIME_UTIL, nightTimeUtil
				);
	}

	public List findBySwitchEditAmount(Object switchEditAmount
			) {
		return findByProperty(SWITCH_EDIT_AMOUNT, switchEditAmount
				);
	}

	public List findBySwitchGratuity(Object switchGratuity
			) {
		return findByProperty(SWITCH_GRATUITY, switchGratuity
				);
	}

	public List findByIsFree(Object isFree
			) {
		return findByProperty(IS_FREE, isFree
				);
	}

	public List findByMinGratuity(Object minGratuity
			) {
		return findByProperty(MIN_GRATUITY, minGratuity
				);
	}

	public List findByCommentCount(Object commentCount
			) {
		return findByProperty(COMMENT_COUNT, commentCount
				);
	}

	public List findByTradeCount(Object tradeCount
			) {
		return findByProperty(TRADE_COUNT, tradeCount
				);
	}

	public List findByAttribution(Object attribution
			) {
		return findByProperty(ATTRIBUTION, attribution
				);
	}

	public List findByBusinessNo(Object businessNo
			) {
		return findByProperty(BUSINESS_NO, businessNo
				);
	}

	public List findByEnterpriseName(Object enterpriseName
			) {
		return findByProperty(ENTERPRISE_NAME, enterpriseName
				);
	}

	public List findByStatus(Object status
			) {
		return findByProperty(STATUS, status
				);
	}


	public List findAll() {
		log.debug("finding all Parkinfo instances");
		try {
			String queryString = "from Parkinfo";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}


	public void attachDirty(Parkinfo instance) {
		log.debug("attaching dirty Parkinfo instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Parkinfo instance) {
		log.debug("attaching clean Parkinfo instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
}